const path = require("path");
const fse = require("fs-extra");

// 文件路径
// /Users/jixiaotai/Desktop/learn/personal-cloud/base/serve/target
const UPLOAD_DIR = path.resolve(__dirname, ".", "target");

// 要生成的文件的路径
const fileName = "weather";
const filePath = path.resolve(UPLOAD_DIR, "..", `${fileName}.jpeg`);

const mergeFileChunk = async (filePath, fileName, size) => {
  // 每一个文件块
  // /Users/jixiaotai/Desktop/learn/personal-cloud/base/serve/target/test
  const chunkDir = path.resolve(UPLOAD_DIR, fileName);
  const chunkPaths = await fse.readdir(chunkDir);
  // [ 'weather-0', 'weather-1', 'weather-2' ]
  chunkPaths.sort((a, b) => a.split("-")[1] - b.split("-")[1]);
  // 创建文件流读每一个文件块
  await Promise.all(
    chunkPaths.map((chunkPath, index) =>
      pipeStream(
        path.resolve(chunkDir, chunkPath),
        fse.createWriteStream(filePath, {
          start: index * size,
          end: (index + 1) * size,
        })
      )
    )
  );
  console.log("文件合并成功");
};

pipeStream = (path, writeStream) =>
  new Promise((resolve) => {
    // 读取文件内容，将文件内容流入可写流
    const readStream = fse.createReadStream(path);
    readStream.on("end", () => {
      // 读完之后
      resolve();
    });
    readStream.pipe(writeStream);
  });
mergeFileChunk(filePath, fileName, 1024 * 1024);
